#include "KPF_StreamSession.h"

KPF_StreamSession::KPF_StreamSession( const int8_t *pIP, const int16u_t iPort )
{
	CSessionParam stSessionParam;
	
	memset( &stSessionParam, 0x00, sizeof(stSessionParam) );
	memcpy( stSessionParam.pIP, (char *)pIP, strlen( (char *) pIP) + 1 );
	stSessionParam.iPort = iPort;
	
	pm_Session = create_session( SESSION_TYPE_STREAM_CLIENT, &stSessionParam );
	if ( pm_Session )
	{
		
		if ( set_session_business( pm_Session, onSessionBusiness, this ) >= 0 )
		{
			if ( set_session_event( pm_Session, onSessionEvent ) >= 0 )
			{
				//log_print( (int8_t *)"create tcp session ok................" );
			}
		}
	}
	else 
		log_print( (int8_t *)"create udp session failed????????????????????????" );
}
	
KPF_StreamSession::~KPF_StreamSession( void )
{
	
}
	
int32_t KPF_StreamSession::handle_input( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	if ( pData && iDataLen > 0 )
	{
		fwrite( pData, 1, iDataLen, stdout );
		fflush( stdout );
		
		iRetCode = 0;	
	}
	
	return iRetCode;
}

int32_t KPF_StreamSession::handle_output( const KPF_Socket *pSocket, const int8u_t *pData, const int32_t iDataLen )
{
	int32_t iRetCode = -1;
	
	iRetCode = send_session_data( pm_Session, pData, iDataLen, NULL );
	
	return iRetCode;
}

int32_t KPF_StreamSession::handle_event( const KPF_Event &eEvent )
{
	int32_t iRetCode = -1;
	
	log_print( (int8_t *)"StreamSession: handle_event------------->" );
	
	if ( EVENT_READ_ERROR == ((KPF_Event)eEvent).getEvent() )
	{
		iRetCode = remove_session_socket( pm_Session, ((KPF_Event)eEvent).getEventParam().pSocket );
		
		destroy_session( pm_Session );
		pm_Session = NULL;
	}
	
	return iRetCode;	
}
